# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import io
import logging
import typing as t

import pandas as pd

from ksai.document.context import DocumentSection
from ksai.document.extractor.extractor import AbstractDocumentExtractor, DocumentExtractorException
from ksai.persistence.storage.attachment import Attachment

logger = logging.getLogger(__name__)


class CsvDocumentExtractor(AbstractDocumentExtractor):

    def __init__(self):
        super().__init__()

    def do_extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        try:
            df = pd.read_csv(io.BytesIO(attachment.content), encoding='utf-8', sep=';')
            df = df.fillna('')
            return [DocumentSection(
                text=df.to_markdown(index=False),
            )]
        except Exception as e:
            raise DocumentExtractorException(f"Extract csv file error: {e}") from e

    def extensions(self) -> t.List[str]:
        return ["csv"]

    def mimes(self) -> t.List[str]:
        return ["text/csv"]
